package myJs.myPkg.rSelect

import japgolly.scalajs.react.CtorType.ChildArg
import japgolly.scalajs.react.facade.React
import japgolly.scalajs.react.vdom.VdomElement
import japgolly.scalajs.react.{Children, JsComponent, JsFnComponent}
import myJs.myPkg.ReactRef
import org.scalajs.dom.html
import slinky.readwrite.ObjectOrWritten

import scala.scalajs.js
import scala.scalajs.js.annotation.JSImport
import scala.scalajs.js.|
import cats.effect._
import cats.effect.unsafe.implicits.global
import japgolly.scalajs.react.util.EffectCatsEffect._

/** Created by yz on 20/9/2023
  */

case class SelectOption(value: String, label: String)

@js.native
trait SelectOptionT extends js.Object {

  val value: js.UndefOr[String] = js.native
  val label: js.UndefOr[String] = js.native

}

object Select {

  @JSImport("react-select", JSImport.Default)
  @js.native
  object RawComponent extends js.Object

  case class Props(
      defaultValue: js.UndefOr[SelectOption] = js.undefined,
      onChange: List[SelectOption] => Unit,
      options: List[SelectOption],
      placeholder: js.UndefOr[String] = js.undefined,
      name: js.UndefOr[String] = js.undefined,
      value: js.UndefOr[List[SelectOption]] = js.undefined,
      ref: js.UndefOr[ReactRef[html.Select]] = js.undefined,
      isClearable: js.UndefOr[Boolean] = js.undefined,
      isMulti: js.UndefOr[Boolean] = js.undefined
  ) {
    @inline def render: VdomElement = {
      Component(this)()
    }
  }

  val Component = JsComponent[ObjectOrWritten[Props], Children.Varargs, Null](RawComponent)

  def apply(
      defaultValue: js.UndefOr[SelectOption] = js.undefined,
      onChange: List[SelectOption] => IO[Unit],
      options: List[SelectOption],
      placeholder: js.UndefOr[String] = js.undefined,
      name: js.UndefOr[String] = js.undefined,
      value: js.UndefOr[List[SelectOption]] = js.undefined,
      ref: js.UndefOr[ReactRef[html.Select]] = js.undefined,
      isClearable: js.UndefOr[Boolean] = js.undefined,
      isMulti: js.UndefOr[Boolean] = js.undefined
  ) = {
    val useOnChange = (so: List[SelectOption]) => onChange(so).unsafeRunAndForget()
    Component(Props(defaultValue, useOnChange, options, placeholder, name, value, ref, isClearable, isMulti))()
  }

}
